/**
 * 
 */
package com.wubo.sec.log;

import com.wubo.sec.SecurityManager;
import com.wubo.sec.core.HttpServletRequestHolder;
import com.wubo.sec.core.UserData;
import com.wubo.sec.model.ActionLog;
import com.wubo.sec.model.ErrorLog;
import com.wubo.sec.model.User;
import com.wubo.sec.util.CharCutter;

/**
 * @author wubo
 * @CreateDate 2010-8-2
 * @version 1.0.01
 */
public abstract class LogHelper {

	private static final int MAX_CHAR_LENGTH = 4000;
	private static final int MAX_DETAIL_LENGTH = 50000;
	
	public static void actionLog(String actionName, String detail){
		 UserData user = SecurityManager.getCurrentUser();
		 if(user instanceof User){
			 actionLog(actionName, detail, (User) user);
		 }
	}
	
	public static void actionLog(String actionName, String detail, User user){
		ActionLog log = new ActionLog();
		log.setActionTime(new java.util.Date());
		log.setUser(user);
		log.setIP(HttpServletRequestHolder.getIP());
		log.setActionName(actionName);
		if(detail != null){
			log.setDetail(CharCutter.cut(detail, MAX_CHAR_LENGTH));
		}
		SecurityManager.log(log);
	}
	
	public static void errorLog(String type, String message, String detail){
		ErrorLog log = new ErrorLog();
		log.setType(type);
		log.setMessage(CharCutter.cut(message, MAX_CHAR_LENGTH));
		log.setOccurTime(new java.util.Date());
		log.setDetail(CharCutter.cut(detail, MAX_DETAIL_LENGTH));
		SecurityManager.log(log);
	}
	
	public static void errorLog(Exception e){
		StringBuilder detail = new StringBuilder();
		StackTraceElement[] stes = e.getStackTrace();
		for(int i=0,leng=stes.length; i<leng; i++){
			StackTraceElement ste = stes[i];
			if((detail.length() + ste.toString().length()) > MAX_DETAIL_LENGTH){
				int len = MAX_DETAIL_LENGTH - detail.length();
				if(len > 3){
					detail.append(ste.toString().substring(0, len - 3));
					detail.append("...");
				}else{
					detail.append("");
				}
				break;
			}
			if(i>0)detail.append("\n");
			detail.append(ste.toString());
		}
		if(e.getMessage().length() > MAX_CHAR_LENGTH){
			errorLog(e.getClass().getName(), e.getMessage().substring(0, MAX_CHAR_LENGTH - 3)+"...", detail.toString());
		}else{
			errorLog(e.getClass().getName(), e.getMessage(), detail.toString());
		}
	}
}
